import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
import { authService, type UserInfo } from '@/lib/auth'

// 认证上下文类型
interface AuthContextType {
  user: UserInfo | null
  isLoading: boolean
  isAuthenticated: boolean
  login: (phone: string, password: string, rememberMe?: boolean) => Promise<void>
  logout: () => Promise<void>
  refreshUser: () => Promise<void>
}

// 创建认证上下文
const AuthContext = createContext<AuthContextType | undefined>(undefined)

// 认证提供者属性
interface AuthProviderProps {
  children: ReactNode
}

// 认证提供者组件
export function AuthProvider({ children }: AuthProviderProps) {
  const [user, setUser] = useState<UserInfo | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isInitialized, setIsInitialized] = useState(false)

  // 计算认证状态
  const isAuthenticated = !!user

  // 初始化认证状态 - 只执行一次
  useEffect(() => {
    if (!isInitialized) {
      initializeAuth()
    }
  }, [isInitialized])

  // 初始化认证状态
  const initializeAuth = async () => {
    try {
      setIsLoading(true)
      
      // 检查本地存储的认证状态
      if (authService.isAuthenticated()) {
        const storedUser = authService.getUserInfo()
        
        // 检查token是否有效
        if (authService.isTokenValid()) {
          setUser(storedUser)
          
          // 跳过自动刷新用户信息，避免在初始化时发起网络请求导致的潜在问题
          // 用户信息刷新可以在需要时手动触发
        } else {
          // token已过期，清除认证信息
          authService.clearAuth()
          setUser(null)
        }
      } else {
        setUser(null)
      }
    } catch (error) {
      console.error('Failed to initialize auth:', error)
      authService.clearAuth()
      setUser(null)
    } finally {
      setIsLoading(false)
      setIsInitialized(true)
    }
  }

  // 登录函数
  const login = async (phone: string, password: string, rememberMe: boolean = false) => {
    try {
      setIsLoading(true)
      const userInfo = await authService.login({ phone, password }, rememberMe)
      setUser(userInfo)
    } catch (error) {
      console.error('Login failed:', error)
      throw error
    } finally {
      setIsLoading(false)
    }
  }

  // 登出函数
  const logout = async () => {
    try {
      setIsLoading(true)
      await authService.logout()
      setUser(null)
    } catch (error) {
      console.error('Logout failed:', error)
      // 即使服务端登出失败，也要清除本地状态
      setUser(null)
    } finally {
      setIsLoading(false)
    }
  }

  // 刷新用户信息
  const refreshUser = async () => {
    try {
      const refreshedUser = await authService.refreshUserInfo()
      if (refreshedUser) {
        setUser(refreshedUser)
      }
    } catch (error) {
      console.error('Failed to refresh user:', error)
      // 如果刷新失败，可能是token已过期，清除认证状态
      authService.clearAuth()
      setUser(null)
    }
  }

  // 上下文值
  const value: AuthContextType = {
    user,
    isLoading,
    isAuthenticated,
    login,
    logout,
    refreshUser,
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}

// 使用认证上下文的Hook
export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}

// 检查是否已认证的Hook（已弃用，使用ProtectedRoute组件代替）
export function useRequireAuth() {
  const { isAuthenticated, isLoading } = useAuth()
  
  // 移除自动重定向逻辑，避免与ProtectedRoute冲突
  // 现在只返回认证状态，重定向逻辑由ProtectedRoute处理
  
  return { isAuthenticated, isLoading }
}
